<?php defined('SYSPATH') or die('No direct access allowed.');

class Controller_Acl extends Controller_Autorization {

    public function before()
	{
	    parent::before();
	}

	public function after()
	{
	    parent::after();
	}

	public function action_index()
	{		//$this->acl = new Acl;
		//new
		//$this->acl2->allow('guest','blog');
		//$this->acl2->deny('guest','blog','read');
		//$this->acl2->allow('owner','blog');
		//$this->acl2->deny('guest','blog');
		//$this->acl2->allow('ОМТС',NULL,'read');
		//echo ($this->acl2->is_allowed('guest','blog','read') ? 'yes' : 'no') . '<br>';
		//echo ($this->acl2->is_allowed('guest','blog','write') ? 'yes' : 'no') . '<br>';
		//echo ($this->acl2->is_allowed('ОМТС','blog','read') ? 'yes' : 'no') . '<br>';
		//echo ($this->acl2->is_allowed('ОМТС','blog','write') ? 'yes' : 'no') . '<br>';
/*
		$this->acl->add_role('super_user',array('user','guest'));
		$this->acl->allow('user','blog');
		echo ($this->acl->is_allowed('super_user','blog') ? 'yes' : 'no') . '<br>';
		echo ($this->acl->is_allowed('user','blog') ? 'yes' : 'no') . '<br>';
		echo ($this->acl->is_allowed('guest','blog') ? 'yes' : 'no') . '<br>';

		// conflicting rules to parents
		$this->acl->allow('user','blog','edit');
		$this->acl->deny('guest','blog','edit');

		echo ($this->acl->is_allowed('super_user','blog','edit') ? 'yes' : 'no') . '<br>';
		echo ($this->acl->is_allowed('user','blog','edit') ? 'yes' : 'no') . '<br>';
		echo ($this->acl->is_allowed('guest','blog','edit') ? 'yes' : 'no') . '<br>';
		exit();
*/

 		$this->body();	}

	public function action_access()
	{
 		$this->get_groups();
 		if ($this->request->is_ajax())
 		{ 			$this->_do(); 		}
 		else
 		{
        //$this->_data['rules'] =


	 		$this->body();
		}
     //$blogs = ORM::factory('blog')->find_all();

        // show user info
        //echo $this->user_info();
/*
        // show blogs
        echo '<hr />';

        if(count($blogs) === 0)
        {
            echo 'No blogs yet<br />';
        }
        else
        {
            foreach($blogs as $blog)
            {
                echo $blog->text . ' by <strong><i>' . $blog->user->username . '</i></strong><br />';
                $e = "";
                $d = "";
                if ($this->user) {
                    $e = ($this->a2->allowed($blog,'edit'))? html::anchor($this->_name.'/edit/'.$blog->id,'Edit') : "";
                    $d = ($this->a2->allowed($blog,'delete'))? ' - '.html::anchor($this->_name.'/delete/'.$blog->id,'Delete') : "";
                }
                echo $e,$d,'<hr />';
            }
        }
        if ($this->user){
          echo html::anchor($this->_name.'/add','Add');
        }*/
	}

	public function action_users()
	{
        $this->del();
		$this->edit();

        if (!empty($_POST))
        {
			$post = Validation::factory($this->request->post());
			$post->rule('addusername', 'not_empty')
				->rule('addusername', 'min_length', array(':value', 3))
				->rule('addusername', 'max_length', array(':value', 32))
				->rule('addusername', 'regex', array(':value', '/^[a-z0-9_.-]++$/iD'))
				->rule('addemail', array('Valid', 'email'))
				->rule('addpassword', 'not_empty')
				->rule('addpassword', 'min_length', array(':value', 4))
				->rule('addpassword', 'max_length', array(':value', 32))
				->rule('confirmpassword',  'matches', array(':validation', 'addpassword', 'confirmpassword'));
			if ($post->check())
			{
				$user = array(
					'logins'=>0,
					'last_login'=>0,
					'last_uri'=>'',
					'id_location'=>0,
				);
				foreach($post->as_array() as $k=>$v)
				{
					if (substr($k,0,3)=='add')
					{
						$k = str_replace('add','',$k);
						if($this->r->hGet($this->_data['action'].':lookup:'.$k,strtolower($v)))
						{
							$this->_data['errors'][$k] = 1;
							break;
						}
						$user[$k] = $v;
					}
				}
				if (empty($this->_data['errors']))
				{
					$user['id'] = $this->r->incr($this->_data['action'].'_last_id');
					$user['password'] = $this->a1->hash_password($user['password']);
					$this->r->multi()
						->set($this->_data['action'].':'.$user['id'],json_encode($user))
						->hSet($this->_data['action'].':lookup:username',strtolower($user['username']),$user['id'])
						->hSet($this->_data['action'].':lookup:email',strtolower($user['email']),$user['id'])
						->exec();
					unset($user);
					$this->redirect();
				}
			}
			else
			{
				// Get errors from messages/forms/login.php
				//echo $errors = $Validation->errors('forms/login');
				$errors = $post->errors('login');
				echo Debug::vars($errors);
				//print_r($user);
			}
        }

		$this->get_users();

        //echo ($this->acl->is_allowed(1,$this->_data['controller'].'/'.$this->_data['action'],'read') ? 'yes' : 'no').'<br />';
        //echo ($this->acl->is_allowed(1,$this->_data['controller'].'/'.$this->_data['action'],'edit') ? 'yes' : 'no').'<br />';
        //echo ($this->acl->is_allowed(1,$this->_data['controller'].'/'.$this->_data['action'],'write') ? 'yes' : 'no').'<br />';
        //exit;

        $this->_data['create'] = View::factory($this->_data['controller'].'/'.$this->_data['action'].'_create');
		$this->body();
	}

	public function action_groups()
	{
		$this->del();

        if (!empty($_POST))
        {
			$post = Validation::factory($this->request->post());
			$post->rule('addgroupname', 'not_empty')
				->rule('addgroupname', 'min_length', array(':value', 3))
				->rule('addgroupname', 'max_length', array(':value', 64))
				->rule('addgroupname', 'regex', array(':value', '/^[а-яa-z0-9][а-яa-z0-9 _.-]++$/uiD'));
			if ($post->check())
			{
				foreach($post->as_array() as $k=>$v)
				{
					if (substr($k,0,3)=='add')
					{
						$k = str_replace('add','',$k);
						if($this->r->hGet($this->_data['action'].':lookup:'.$k,strtolower($v)))
						{
							$this->_data['errors'][$k] = 1;
							break;
						}
						$group[$k] = $v;
					}
				}

				if (empty($this->_data['errors']))
				{
					$group['id'] = $this->r->incr($this->_data['action'].'_last_id');
					$this->r->multi()
						->set($this->_data['action'].':'.$group['id'],json_encode($group))
						->hSet($this->_data['action'].':lookup:groupname',$group['groupname'],$group['id'])
						->exec();

					unset($group);
				}
				$this->redirect();
			}
			else
			{
				// Get errors from messages/forms/login.php
				//echo $errors = $Validation->errors('forms/login');
				$errors = $post->errors('login');
				echo Debug::vars($errors);
				//print_r($user);
			}
        }

		$this->get_groups();
		$this->_data['create'] = View::factory($this->_data['controller'].'/'.$this->_data['action'].'_create');
 		$this->body();
	}

	public function action_usersgroups()
	{
		if (!empty($_POST['usersgroups']))
		{			foreach($this->r->keys('group_users:[0-9]*') as $group_users)
			{
				$this->r->del($group_users);
			}
			foreach($this->r->keys('user_groups:[0-9]*') as $user_groups)
			{
				$this->r->del($user_groups);
			}

			$multi = $this->r->multi();
			foreach($this->request->post('usersgroups') as $user=>$groups)
			{				foreach($groups as &$group)
				{
					if (!empty($group))
					{
						$multi->sAdd('group_users:'.$group,$user); // добавляем в группу $group пользователя с id = $user
						$multi->sAdd('user_groups:'.$user,$group); // добавляем пользователю $user группу с id = $group
					}
				}			}
			$multi->exec();
			$this->response->body('ok');		}
		else
		{
			$this->get_users();
			$this->get_groups();
	 		$this->body();
		}
	}

	private function get_users()
	{
 		$this->_data['users'] = array();
		foreach($this->r->keys('users:[0-9]*') as $user)
		{
			$obj = json_decode($this->r->get($user));
			if ($obj->id==1)
			{
				continue;
			}
			$this->_data['users'][str_replace('users:','',$user)] = $obj;
		}
	}

	private function get_groups()
	{
		$this->_data['groups'] = array();
		foreach($this->r->keys('groups:[0-9]*') as $group)
		{
			$this->_data['groups'][str_replace('groups:','',$group)] = json_decode($this->r->get($group));
		}
	}

	private function redirect()
	{		$this->request->redirect($this->_data['controller'].'/'.$this->_data['action']);	}

	private function del()
	{		if ($this->_data['do'] AND $this->_data['do']=='del')
		{
			if (($this->_data['id']<=1 AND $this->_data['action']=='users') OR ($this->_data['id']<1 AND $this->_data['action']=='groups') OR !$this->r->exists($this->_data['action'].':'.$this->_data['id']))
			{
				$this->redirect();
			}
			$obj = json_decode($this->r->get($this->_data['action'].':'.$this->_data['id']));
			//print_r($obj);
			//exit();
			$keys = $this->r->keys($this->_data['action'].':lookup:*');
			$multi = $this->r->multi();
			$multi->del($this->_data['action'].':'.$obj->id);

			foreach($keys as &$key)
			{
				$param = str_replace($this->_data['action'].':lookup:','',$key);
				$multi->hDel($key,$obj->{$param});
			}
			$multi->exec();
			$this->redirect();
		}	}

	// Контрагенты
	public function action_partner()
	{
        $this->del();
		$this->edit();

        if (!empty($_POST))
        {
		}
        $this->body();
	}
	// Контрагенты END

	//регистрация контрагентов
	
		public function action_partnercreate()
	{
		// если метод запроса POST и выполненн с использованием AJAX
		if ($this->request->method() == Request::POST AND $this->request->is_ajax())
		{ 
		}
		else
		{
			//$header = View::factory('partner/parthner_header',$this->_data);
			$body = View::factory('acl/partnercreate',$this->_data);
			//$footer = View::factory('parthner/parthner_footer',$this->_data);
			//$this->response->body($body);
		}
		$this->body();
	}

	
	//Регистрация контрагентов END
	
	
	
	

	private function edit()
	{
		if ($this->_data['do'] AND $this->_data['do']=='edit')
		{
			if (($this->_data['id']<=1 AND $this->_data['action']=='users') OR ($this->_data['id']<1 AND $this->_data['action']=='groups') OR !$this->r->exists($this->_data['action'].':'.$this->_data['id']))
			{
				$this->redirect();
			}
			$obj = json_decode($this->r->get($this->_data['action'].':'.$this->_data['id']));
			print_r($obj);
			exit();
			$keys = $this->r->keys($this->_data['action'].':lookup:*');
			$multi = $this->r->multi();
			$multi->del($this->_data['action'].':'.$obj->id);

			foreach($keys as &$key)
			{
				$param = str_replace($this->_data['action'].':lookup:','',$key);
				$multi->hDel($key,$obj->{$param});
			}
			$multi->exec();
			$this->redirect();
		}
	}



	private function _do()
	{
		// если запрос на типа access
		if ($this->_data['id'] AND $this->_data['id']>0 AND $this->_data['do'] AND $this->_data['do']=='access' AND $this->r->exists('groups:'.$this->_data['id']))
		{
			// возвращаем данные правил для группы
			$obj = json_decode($this->r->get('groups:'.$this->_data['id']));
			//$this->_data['rules'] = $obj->rules;
			$this->response->body(json_encode(get_object_vars($obj)));
			//return $obj->rules;
		}
		// если запрос типа rules
		elseif (Request::current()->method() == Request::POST AND !empty($_POST['rules']) AND $this->_data['id'] AND $this->_data['id']>0 AND $this->_data['do'] AND $this->_data['do']=='rules' AND $this->r->exists('groups:'.$this->_data['id']))
		{
			// получаем данные правил для группы
			$obj = json_decode($this->r->get('groups:'.$this->_data['id']));
			//print_r(get_object_vars($obj));
			$obj->rules = $this->request->post('rules');
			//print_r(get_object_vars($obj));
			//exit();
			$this->r->set('groups:'.$this->_data['id'],json_encode(get_object_vars($obj)));
			//return $obj->access;
		}
		else
		{			//$this->redirect();		}	}
/*
	public function action_login()
	{
		if($this->user) //cannot create new accounts when a user is logged in
		{
			return $this->action_index();
		}

		$post = Validation::factory($_POST)
			->rule('username', 'not_empty')
			->rule('username', 'min_length', array(':value', 3))
			->rule('username', 'max_length', array(':value', 32))
			->rule('password', 'not_empty')
			->rule('password', 'min_length', array(':value', 6))
			->rule('password', 'max_length', array(':value', 32));

		if($post->check())
		{
			//echo '<br />checked';
			if($this->a1->login($post['username'],$post['password'], isset($_POST['remember']) ? (bool) $_POST['remember'] : FALSE))
			{
				$this->request->redirect($this->_name.'/index' );
			}
		}

		//show form
		echo form::open();
		echo 'username:' . form::input('username') . '<br>';
		echo 'password:' . form::password('password') . '<br>';
		echo 'remember me:' . form::checkbox('remember',TRUE) . '<br>';
		echo form::submit('login','login');
		echo form::close();
		echo Debug::vars($post->errors());

	}

	public function action_logout()
	{
		$this->a1->logout();
		$this->user = NULL;
		return $this->action_index();
	}

	public function action_add()
	{
		if(!$this->a2->allowed('blog','add'))
		{
			echo '<b>You are not allowed to add blogs</b><br>';
			return $this->action_index();
		}

		$blog = ORM::factory('blog');

		$this->editor($blog);
	}

	public function action_edit($blog_id)
	{
		$blog = ORM::factory('blog',$blog_id);

		// NOTE the use of the actual blog object in the allowed method call!
		if(!$this->a2->allowed($blog,'edit'))
		{
			echo '<b>You are not allowed to edit this blog</b><br>';
			return $this->action_index();
		}

		$this->editor($blog);
	}

	private function editor($blog)
	{
		if(count($_POST))
		{
			$blog->values($_POST);

			if($blog->check())
			{
				// Check if user_id is not empty, that means an admin is editing
				$blog->user_id = (empty($blog->user_id))? $this->a2->get_user()->id : $blog->user_id;
				$blog->save();
				return $this->action_index();
			}
		}

		//show form
		echo form::open();
		echo 'text:' . form::textarea('text',$blog->text) . '<br>';
		echo form::submit('post','post');
		echo form::close();
		echo Kohana::debug($blog->validate()->errors());

	}

	public function action_delete($blog_id)
	{
		$blog = ORM::factory('blog',$blog_id);

		// NOTE the use of the actual blog object in the allowed method call!
		if(!$this->a2->allowed($blog,'delete'))
		{
			echo '<b>You are not allowed to delete this blog</b><br>';
		}
		else
		{
			$blog->delete();
		}

		$this->action_index();
	}
*/
/*
	private function user_info()
	{
        $s = "Use admin:admin (username:password) for Admin role. Use author:author (username:password) for Author role <br />";
        if( $this->user )
        {
            $s .=  '<b><i>'.$this->user->username.' </i></b> ' . html::anchor($this->_data['controller'].'/logout','Logout');
        }
        else
        {
            $s .= '<b>Guest</b> ' . html::anchor($this->_data['controller'].'/login','Login') . ' - ' . html::anchor($this->_data['controller'].'/create','Create account');
        }

		return '<div style="width:95%;padding:5px;background-color:#AFB6FF;">' . $s . '</div>';
	}
*/
/*	public function action_create()
	{

	    if($this->user) //cannot create new accounts when a user is logged in
		{
			//$this->action_index();
		}

        if (!empty($_POST))
        {
			$post = $_POST;

			// Create a new user
			$user = ORM::factory('user')
				->values($post);

			if ($user->check())
			{
			    // Saving login role and the one coming from dropdown menu
        	    $user->save();
       		    $user->add('roles', ORM::factory('role', array('name' => 'login')));
        	    $user->add('roles', ORM::factory('role', array('id' => $post['role'])));

				// user  created, show login form
				$this->action_login();
			}
		    echo Debug::vars($user->validation()->errors());
		}
		else
		{
		    //show form





		}
 		$header = View::factory('page/bootstrap_header',$this->_data);
		$body = View::factory($this->_data['controller'].'/'.$this->_data['action'],$this->_data);
		$footer = View::factory('page/bootstrap_footer',$this->_data);
		$this->response->body($header.$body.$footer);
	}
*/

}